import TitleBar from "@/components/TitleBar/TitleBar";
import { useRef, useState } from "react";
//导入uuid,生我们生成唯一的字符串
import { v4 as uuidv4 } from "uuid";
import { produce } from "immer";
import UserMessageItem from "@/components/UserMessageItem/UserMessageItem";
import AssistantMessageItem from "@/components/AssistantMessageItem/AssistantMessageItem";
//produce它可以根据旧数据来生产新数据，而react里面的状态变化不就是要用新数据替换旧数据

const Chat = () => {
    const [inputMsg, setInputMsg] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [messageList, setMessageList] = useState([]);
    const scrollRef = useRef();

    /**
     * 发送问题
     */
    const sendQuestion = () => {
        if (inputMsg.trim().length === 0) {
            return;
        }
        if (isLoading) {
            return;
        }
        setIsLoading(true);
        //第1步：构建消息
        let userMessage = {
            id: uuidv4(),
            role: "user",
            create_at: Date.now(),
            content: inputMsg
        }
        let assistantMessage = {
            id: uuidv4(),
            role: "assistant",
            create_at: Date.now(),
            content: ""
        }

        setMessageList(produce((draft) => {
            draft.push(userMessage);
            draft.push(assistantMessage);
        }));


        //第2步：将消息发送到AI服务器
        let u = "http://www.softeem.xin:9898/baiduAPI/stream/chat";
        fetch(u, {
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8"
            },
            body: JSON.stringify({
                content: inputMsg
            })
        }).then(resp => {
            let reader = resp.body.getReader();
            let textDecoder = new TextDecoder();
            const processData = () => {
                reader.read().then(result => {
                    let text = textDecoder.decode(result.value);
                    let josnStr = text.replace(/data: /g, "").trim();
                    if (josnStr) {
                        let jsonObj = JSON.parse(josnStr);
                        //将消息追加到最后一条的AI消息内容里面
                        setMessageList(produce((draft) => {
                            draft[draft.length - 1].content += jsonObj.result
                        }));
                        //将滚动条滚动到最下面
                        scrollRef.current.scrollTop = scrollRef.current.scrollHeight;

                    }
                    if (!result.done) {
                        processData();
                    }
                });
            };
            processData();
        }).catch(error => {
            console.log(error);
        }).finally(() => {
            setIsLoading(false);
        });
        //将输入框清空
        setInputMsg("");
    }

    const buildMessageList = () => {
        return messageList.map(item => {
            if (item.role === "user") {
                return <UserMessageItem key={item.id} itemData={item} />
            }
            else if (item.role === "assistant") {
                return <AssistantMessageItem key={item.id} itemData={item} />
            }
        })
    }

    /**
     * 处理回车操作
     * @param {MouseEvent} event 
     */
    const handleKeyDown = event => {
        if (event.key === "Enter") {
            sendQuestion();
        }
    }

    return <div className="w-full h-full overflow-auto flex flex-col">
        <TitleBar title="智能小助手" />
        <div ref={scrollRef} className="flex-1 overflow-auto bg-[#EEEEEE] box-border px-[5px]">
            {buildMessageList()}
        </div>
        <div className="h-[50px] bg-white flex flex-row items-center box-border px-[10px] py-[5px] gap-[10px]">
            <input
                value={inputMsg}
                onInput={(event) => {
                    setInputMsg(event.target.value)
                }}
                type="text"
                placeholder="快来输入你的问题吧"
                className="box-border px-[4px] flex-1 outline-0 h-full bg-gray-100"
                onKeyDown={event => handleKeyDown(event)} />
            <span
                onClick={sendQuestion}
                className="iconfont icon-zhifeiji text-[26px] text-primary-color transition-all active:scale-90 active:text-green-400"></span>
        </div>
    </div>
}
export default Chat;